<template>
  <div class="login-mobile">
    <div class="login-container">
      <div class="login-card">
        <div class="logo-section">
          <img src="/fylog1d.png" alt="Logo" class="logo" />
          <h1 class="app-title">柳州市妇幼保健院</h1>
        </div>
        
        <div class="login-form">
        <div class="form-group">
          <input
            v-model="loginForm.username"
            type="text"
            placeholder="请输入用户名"
            class="form-input"
            :disabled="loading"
          />
        </div>
        
        <div class="form-group">
          <input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            class="form-input"
            :disabled="loading"
            @keyup.enter="handleLogin"
          />
        </div>
        
        <!-- 图形验证码 -->
        <div class="form-group captcha-group">
          <div class="captcha-container">
            <img 
              v-if="captchaImage" 
              :src="captchaImage" 
              alt="验证码" 
              class="captcha-image"
              @click="refreshCaptcha"
            />
            <div v-else class="captcha-loading">加载中...</div>
            <button 
              type="button" 
              @click="refreshCaptcha" 
              class="refresh-btn"
              :disabled="loading"
            >
              刷新
            </button>
          </div>
          <input
            v-model="loginForm.captcha"
            type="text"
            placeholder="请输入验证码"
            class="form-input captcha-input"
            :disabled="loading"
            maxlength="4"
          />
        </div>
        
        <button
          @click="handleLogin"
          :disabled="loading || !loginForm.username || !loginForm.password || !loginForm.captcha"
          class="login-btn"
        >
          <span v-if="loading">登录中...</span>
          <span v-else>登录</span>
        </button>
        
        <!-- 企业微信登录按钮 -->
        <div class="wechat-login-section">
          <div class="divider">
            <span>或</span>
          </div>
                      <!-- v-if="loginForm.username === '201088'" -->
          <button
            @click="startWeChatLogin"
            class="wechat-work-btn"
            :disabled="loading || wechatLoading"
          >
            <span v-if="wechatLoading" class="loading-spinner-small"></span>
            <span v-else class="btn-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="white">
                <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 4.882-1.786 7.608-.925.847-3.206-2.233-5.921-8.351-5.921zm-2.262 5.924a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433zm4.524 0a.716.716 0 1 1 0-1.433.716.716 0 0 1 0 1.433z"/>
                <path d="M15.309 11.468c-3.506 0-6.266 2.749-6.266 6.109 0 1.672.8 3.109 2.05 4.075a.402.402 0 0 1 .146.46l-.271 1.026c-.013.049-.034.098-.034.147 0 .113.092.204.201.204a.226.226 0 0 0 .116-.037l1.32-.772a.6.6 0 0 1 .497-.068c.758.232 1.55.342 2.241.342 3.506 0 6.266-2.749 6.266-6.109s-2.76-6.377-6.266-6.377zm-1.758 4.108a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992zm3.517 0a.496.496 0 1 1 0-.992.496.496 0 0 1 0 .992z"/>
              </svg>
            </span>
            <span v-if="wechatLoading">正在跳转...</span>
            <span v-else>企业微信登录</span>
          </button>
        </div>

      </div>
      </div>
      
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { isWeChatWork } from '@/utils/wechat'
import { initVConsole } from '@/utils/vconsole'
import api from '@/utils/api'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const loading = ref(false)
const wechatLoading = ref(false)

const errorMessage = ref('')
const isWeChatWorkEnv = ref(false)
const captchaImage = ref('')
const sessionId = ref('')

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

// 监听用户名输入变化，触发vConsole初始化检查
watch(() => loginForm.username, (newValue) => {
  // 当输入特殊用户名时，触发vConsole检查
  if (newValue === '20108' || newValue === '18013') {
    console.log('检测到调试用户名，触发vConsole检查...')
    // 模拟用户登录状态变化
    localStorage.setItem('user', JSON.stringify({ username: newValue }))
    window.dispatchEvent(new Event('userLoginStatusChanged'))
  } else {
    // 清除测试用户
    localStorage.removeItem('user')
    window.dispatchEvent(new Event('userLoginStatusChanged'))
  }
})

// 页面初始化
onMounted(async () => {
  // 检测企业微信环境
  isWeChatWorkEnv.value = isWeChatWork()
  
  // 加载验证码
  loadCaptcha()
  
  // 检查企业微信回调参数
  await checkWeChatWorkCallback()
})

// 加载验证码
const loadCaptcha = async () => {
  try {
    const result = await authStore.getCaptcha()
    if (result.success) {
      captchaImage.value = result.data.image
      sessionId.value = result.data.sessionId
    } else {
      errorMessage.value = result.message || '获取验证码失败'
    }
  } catch (error) {
    console.error('加载验证码失败:', error)
    errorMessage.value = '获取验证码失败，请刷新页面'
  }
}

const handleLogin = async () => {
  if (!loginForm.username || !loginForm.password) {
    errorMessage.value = '请输入用户名和密码'
    return
  }
  
  if (!loginForm.captcha) {
    errorMessage.value = '请输入验证码'
    return
  }
  
  // 验证码将在服务端验证
  
  try {
    loading.value = true
    errorMessage.value = ''
    
    const result = await authStore.login({
      username: loginForm.username,
      password: loginForm.password,
      captcha: loginForm.captcha,
      sessionId: sessionId.value
    })
    
    if (result.success) {
      // 登录成功，跳转到主页
      router.push('/')
    } else {
      errorMessage.value = result.message || '登录失败，请检查用户名和密码'
      
      // 如果是账户锁定，不刷新验证码，只清空验证码输入
      if (result.isLocked) {
        loginForm.captcha = ''
      } else {
        // 其他登录失败情况刷新验证码
        loginForm.captcha = ''
        refreshCaptcha()
      }
    }
    
  } catch (error) {
    console.error('登录失败:', error)
    errorMessage.value = error.message || '登录失败，请检查用户名和密码'
    // 登录失败时刷新验证码
    loginForm.captcha = ''
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = async () => {
  loginForm.captcha = ''
  await loadCaptcha()
}

// 企业微信登录功能
const startWeChatLogin = async () => {
  try {
    wechatLoading.value = true
    errorMessage.value = ''
    
    // 获取授权URL
    const state = generateState()
    const response = await api.post('/api/wechatwork/auth-url', {
      redirectUri: null,
      state: state
    })
    
    if (response.data.success) {
      // 跳转到企业微信授权页面
      window.location.href = response.data.data.authUrl
    } else {
      errorMessage.value = response.data.message || '获取授权链接失败'
    }
  } catch (err) {
    console.error('企业微信登录失败:', err)
    errorMessage.value = '网络错误，请检查网络连接'
  } finally {
    wechatLoading.value = false
  }
}

// 检查企业微信回调
const checkWeChatWorkCallback = async () => {
  const code = route.query.code
  const state = route.query.state
  const token = route.query.token
  const errorParam = route.query.error
  const message = route.query.message
  
  if (errorParam) {
    // 处理错误回调
    errorMessage.value = decodeURIComponent(message || '企业微信登录失败')
  } else if (token) {
    // 处理成功回调
    await handleWeChatSuccessCallback(token, route.query.userId, route.query.name)
  } else if (code) {
    // 处理授权码回调
    await handleWeChatCodeCallback(code, state)
  }
}

// 处理企业微信授权码回调
const handleWeChatCodeCallback = async (code, state) => {
  try {
    loading.value = true
    
    // 调用登录API
    const response = await api.post('/api/wechatwork/login', {
      code: code,
      state: state
    })
    
    if (response.data.success && response.data.data.success) {
      const loginData = response.data.data
      await handleWeChatLoginSuccess(loginData)
    } else {
      const message = response.data.data?.message || response.data.message || '企业微信登录失败'
      errorMessage.value = message
    }
  } catch (err) {
    console.error('处理授权码失败:', err)
    errorMessage.value = '登录验证失败，请重试'
  } finally {
    loading.value = false
  }
}

// 处理企业微信成功回调
const handleWeChatSuccessCallback = async (token, userId, name) => {
  try {
    loading.value = true
    
    // 保存token到store
    await authStore.setWeChatWorkToken(token, {
      userId: userId,
      name: decodeURIComponent(name || '')
    })
    
    // 跳转到主页
    router.push('/')
  } catch (err) {
    console.error('处理成功回调失败:', err)
    errorMessage.value = '登录完成失败，请重试'
  } finally {
    loading.value = false
  }
}

// 处理企业微信登录成功
const handleWeChatLoginSuccess = async (loginData) => {
  try {
    // 通过企业微信用户ID获取正确的用户信息
    const correctedUserInfo = await syncWeChatWorkUserInfo(loginData.userInfo.id)
    
    if (correctedUserInfo) {
      // 使用修正后的用户信息
      const updatedUserInfo = {
        ...loginData.userInfo,
        username: correctedUserInfo.username,
        fullName: correctedUserInfo.fullName,
        userPhone: correctedUserInfo.userPhone,
        id: correctedUserInfo.userId
      }
      
      // 保存token和修正后的用户信息到store（会自动获取权限）
      await authStore.setWeChatWorkToken(loginData.token, updatedUserInfo)
      
      console.log('企业微信登录成功，用户信息和权限已保存')
    } else {
      // 如果获取用户信息失败，使用原始信息但给出警告
      console.warn('获取用户详细信息失败，使用原始企业微信信息')
      await authStore.setWeChatWorkToken(loginData.token, loginData.userInfo)
    }
    
    // 跳转到主页
    router.push('/')
  } catch (err) {
    console.error('保存登录信息失败:', err)
    errorMessage.value = '保存登录信息失败，请重试'
  }
}

// 同步企业微信用户信息
const syncWeChatWorkUserInfo = async (wxUserId) => {
  try {
    // 第一步：通过企业微信用户ID获取用户名
    const usernameResponse = await api.post('/api/wechatwork/get-username-by-wxuserid', {
      wxUserId: wxUserId
    })
    
    if (!usernameResponse.data.success) {
      console.error('获取用户名失败:', usernameResponse.data.message)
      return null
    }
    
    const username = usernameResponse.data.username
    
    // 第二步：通过用户名获取用户详细信息
    const userDetailResponse = await api.post('/api/wechatwork/get-user-detail-by-username', {
      username: username
    })
    
    if (!userDetailResponse.data.success) {
      console.error('获取用户详细信息失败:', userDetailResponse.data.message)
      return null
    }
    
    const userDetail = userDetailResponse.data.data
    
    return {
      username: userDetail.username,
      fullName: userDetail.fullName,
      userPhone: userDetail.userPhone,
      userId: userDetail.userId
    }
  } catch (error) {
    console.error('同步企业微信用户信息失败:', error)
    return null
  }
}

// 生成状态参数
const generateState = () => {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}




</script>

<style scoped>
.login-mobile {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 16px;
  padding: 40px 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.captcha-group {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  justify-content: center;
}

.captcha-image {
  width: 200px;
  height: 60px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.captcha-image:hover {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.captcha-loading {
  width: 200px;
  height: 60px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  color: #6c757d;
  font-size: 14px;
}

.refresh-btn {
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  color: #495057;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.refresh-btn:hover:not(:disabled) {
  background: #e9ecef;
  border-color: #adb5bd;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.captcha-input {
  text-align: center;
  letter-spacing: 2px;
  font-weight: 600;
}

.form-input {
  width: 100%;
  height: 50px;
  padding: 0 16px;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
}

.form-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.wechat-login-section {
  margin-top: 20px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  color: #999;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #e0e0e0;
}

.divider span {
  padding: 0 15px;
}

.wechat-work-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #07C160 0%, #00A854 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.wechat-work-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(7, 193, 96, 0.4);
}

.wechat-work-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}



.btn-icon {
  display: flex;
  align-items: center;
}

.loading-spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}



.error-message {
  background-color: #fee;
  color: #c53030;
  padding: 12px;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  border: 1px solid #fed7d7;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .login-mobile {
    padding: 10px;
  }
  
  .login-card {
    padding: 30px 20px;
  }
  
  .app-title {
    font-size: 20px;
  }
  
  .form-input,
  .login-btn {
    height: 45px;
    font-size: 15px;
  }
}
</style>